/*
    12. Write a program in C to merge two files and write it in a new file. 

    Assume that the content of the file test.txt and test1.txr is :                                                                       
    The content of the file test.txt is  : 
    This is the file test.txt. 

    The content of the file test1.txt is  : 
    This is the file test1.txt.                                                                                                    
    Test Data :
    Input the 1st file name : test.txt
    Input the 2nd file name : test1.txt
    Input the new file name where to merge the above two files : mergefiles.txt
    Expected Output :

    The two files merged into mergefiles.txt file successfully..!! 
    Here is the content of the merge file mergefiles.txt :

    The content of the file mergefiles.txt is  :                                                                 
    This is the file test.txt.                                                                                    
    This is the file test1.txt.
*/

#include <stdio.h>

#define MAX_STR 1024

int main(void)
{
    FILE *fp1, *fp2, *fpm;
    char fname1[64];
    char fname2[64];
    char mname[64];
    char str[MAX_STR];

    printf("Input the 1st file name : ");
    gets(fname1);
    printf("Input the 2nd file name : ");
    gets(fname2);
    printf("Input the new file name where to merge above two files : ");
    gets(mname);

    fp1 = fopen(fname1, "r");
    if(!fp1){
        printf("Open file %s error!", fname1);
        return -1;
    }
    fp2 = fopen(fname2, "r");
    if(!fp2){
        printf("Open file %s error!", fname2);
        return -1;
    }
    fpm = fopen(mname, "w+");
    if(!fpm){
        printf("Open file %s error!", mname);
        return -1;
    }

    while(fgets(str, MAX_STR, fp1)){
        fputs(str, fpm);
    }
    while(fgets(str, MAX_STR, fp2)){
        fputs(str, fpm);
    }

    fclose(fp1);
    fclose(fp2);
    fclose(fpm);
    
    return 0;
}